package cn.edu.flink.tutorial.checkpoint;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.runtime.state.filesystem.FsStateBackend;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Objects;

/**
 * flink run -c cn.edu.flink.checkpoint.Checkpointing  flink-tutorial-1.0-SNAPSHOT.jar
 * flink run -s /Users/wangkang185/flink/checkpoint/fb335ca50a8e824066c91c650f2b0cb2/chk-734/_metadata -c cn.edu.flink.checkpoint.Checkpointing  flink-tutorial-1.0-SNAPSHOT.jar
 */
public class Checkpointing {
    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 开启Checkpoint
        env.enableCheckpointing(1000);
        // 设置状态后端
        env.setStateBackend(new FsStateBackend("file:///Users/wangkang185/flink/checkpoint"));
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);
        env.getCheckpointConfig().setCheckpointTimeout(60000);

        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);

        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(1, 10000));

        // nc -lk 9100
        DataStream<String> source = env.socketTextStream("localhost", 9100).name("MySourceFunction");

        SingleOutputStreamOperator<Tuple2<String, Integer>> wordDS = source
                .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> collector) throws Exception {
                        // 失败信号
                        if (Objects.equals(value, "ERROR")) {
                            throw new RuntimeException("custom error flag, restart application");
                        }
                        for (String word : value.split("\\s")) {
                            collector.collect(Tuple2.of(word, 1));
                        }
                    }
                });

        KeyedStream<Tuple2<String, Integer>, String> wordKeyedStream = wordDS
                .keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
                    @Override
                    public String getKey(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
                        return stringIntegerTuple2.f0;
                    }
                });

        wordKeyedStream.sum(1).print();

        env.execute("RestoreCheckpointExample");
    }

}
